<script setup lang="ts">
  import { loginByPasswordAPI } from '@/api/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
  //
  const store = useUserStore()
  // 表单数据
  const loginForm = ref({
    mobile: '13230000001',
    password: 'abc12345',
  })
  //勾选协议
  const isChecked = ref(false)
  // 表单实例
  const loginRef = ref<UniHelper.UniFormsInstance>()
  // 表单验证规则
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: /^1\d{10}$/, errorMessage: '手机号码格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入密码' },
        { pattern: /^[a-zA-Z]{3}\d{5}$/, errorMessage: '密码格式不正确' },
      ],
    },
  }
  // 表单提交
  const onSubmit = async () => {
    if (!isChecked.value) {
      return uni.showToast({ title: '请先勾选协议', icon: 'none' })
    }
    await loginRef.value!.validate!()
    const res = await loginByPasswordAPI(loginForm.value)
    store.token = res.token
    store.userId = res.id!
    uni.showToast({ title: '登录成功' })
    uni.switchTab({ url: '/pages/index/index' })
  }
</script>

<template>
  <uni-forms :model="loginForm" ref="loginRef" :rules="formRules" class="login-form">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="loginForm.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        v-model="loginForm.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isChecked" @click="isChecked = !isChecked" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
